package com.ctgu.fcftsystem.controller;

import org.mybatis.logging.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;

@RestController
@RequestMapping("/DatabaseController")
public class DatabaseController {

    String filePath="C:\\BackupDatabase\\";
    String dbName="financial_db";
    String username="root";
    String password="123456";

    @RequestMapping("/backup")
    public String backupdatabase() throws Exception{
        String backDate= new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName= dbName+"_"+backDate+".sql";
        String command ="mysqldump -u" + username + " -p" + password + " " + dbName + " -r " + filePath + "/" + fileName;
        File backfile = new File(filePath);
        if (!backfile.exists()){
            backfile.mkdirs();
        }

        try {
            Process process = Runtime.getRuntime().exec(command);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @GetMapping("/download")
    public Map downloadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> map = new HashMap<>();
        String fileName = backupdatabase();
        Thread.currentThread().sleep(2000);
        if (!fileName.equals("error")) {
            File file = new File(filePath+fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    map.put("code",0);
                    map.put("msg","数据备份成功！");
                    return map;
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        map.put("code",1);
        map.put("msg","数据备份失败！");
        return map;
    }

    @RequestMapping("/restore")
    public String restoredatabase() throws Exception{
        String fileName= dbName+".sql";
        String command ="cmd /c mysql -u" + username + " -p" + password + " " + dbName + " < " + filePath + "/" + fileName;
        File file = new File(filePath+fileName);
        if (file.exists()){
            try {
                Process process = Runtime.getRuntime().exec(command);
                return "success";
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
        }else{
            return "error";
        }
    }


    @RequestMapping("/upload")
    public Map upload(@RequestParam("file") MultipartFile file) {
        Map<String,Object> map = new HashMap<>();
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            if (!suffixName.equals(".sql")){
                map.put("code",1);
                map.put("msg","文件格式错误，请上传.sql文件");
                return map;
            }
            // 设置文件存储路径
            String path = filePath + dbName + suffixName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            Thread.currentThread().sleep(2000);
            String result = restoredatabase();
            if(result.equals("success")){
                map.put("code",0);
                map.put("msg","恢复数据库成功！");
            }else{
                map.put("code",1);
                map.put("msg","文件上传成功，但恢复数据库失败！");
            }
            return map;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("code",1);
        map.put("msg","文件上传失败！");
        return map;
    }
}
